# -*- coding: iso-8859-1 -*-
#
#    This is part of Malvinas Argentinas Messenger
#
#    Malvinas Argentinas Messenger is free software; you can redistribute
#    it and/or modify it under the terms of the GNU General Public License
#    as published by the Free Software Foundation; either version 2 of the
#    License, or (at your option) any later version.
#
#    Malvinas Argentinas Messenger is distributed in the hope that it will be
#    useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Malvinas Argentinas Messenger; if not, write to the Free
#    Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
#    MA  02110-1301  USA

from protocol import msncb, msnlib, msndp, msnft
import base64
import urllib
import time
import datetime
import string
import os
import gettext
_ = gettext.gettext

def buildCallbacks(system):
	global mam
	mam = system
	
	mam.m.cb.iln = cb_iln
	mam.m.cb.nln = cb_nln
	mam.m.cb.fln = cb_fln
	mam.m.cb.out = cb_out
	mam.m.cb.rng = cb_rng
	mam.m.cb.joi = cb_joi
	mam.m.cb.bye = cb_bye
	mam.m.cb.msg = cb_msg
	mam.m.cb.err = cb_err
	mam.m.cb.qng = cb_qng
	mam.m.cb.add = cb_add
	mam.m.cb.rem = cb_rem
	mam.m.cb.adg = cb_adg
	mam.m.cb.rmg = cb_rmg
	mam.m.cb.reg = cb_reg
	mam.m.cb.rea = cb_rea


#-------------------
# List of callbacks
#-------------------

def cb_iln(md, type, tid, params):
	t = params.split(' ')		
	status = msnlib.reverse_status[t[0]]
	email = t[1]
	rnick = urllib.unquote(t[2])	

	if int(mam.config['show_groups']) == 1:
		for g in mam.contactListManager.gList.grupos:
			found = 0
			for p in g.passports.passports:
				if p.name == email:
					found = 1
					p.set_status(t[0])
					if rnick <> p.realnick:
						mam.m.userren(email, rnick)
						p.set_realnick(rnick)
					if email not in mam.aliasesList.keys():
						p.set_nick(rnick)	# If not user defined
					break
			if found:
				break
	
	else:
		for p in mam.contactListManager.pList.passports:
			if p.name == email:
				p.set_status(t[0])
				if rnick <> p.realnick:
					mam.m.userren(email, rnick)
					p.set_realnick(rnick)
				if email not in mam.aliasesList.keys():
					p.set_nick(rnick)	# If not user defined
				break

	# In case I didnt get all of the ILN's yet
	if mam.connectionManager.listOK:
		mam.ui.scrList.build_entire_scrList()
		mam.ui.scrList.build_visible_scrList()
		if mam.ui.options_index == -1:
			mam.ui.scrList.print_scrList()
		else:
			mam.ui.rebuild_contactList_whileinMenu()		
		mam.ui.refreshScr(0, 0, 0, 1)
	msncb.cb_iln(md, type, tid, params)

def cb_rea(md, type, tid, params):
	t = params.split(' ')
	email = t[1]
	if email == mam.m.email:
		nick = urllib.unquote(t[2])
		ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
		mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		mam.ui.printMsg('%s ' % _('Nick changed to'), mam.ui.COLORS.BLUE_R)
		mam.ui.printMsg('"%s"' % nick, mam.ui.COLORS.WHITE_R)
		mam.ui.padArray.refresh(_('EVENTS'))
	msncb.cb_rea(md, type, tid, params)

def cb_nln(md, type, tid, params):
	status = _(msnlib.reverse_status[tid])
	t = params.split(' ')
	email = t[0]
	if len(params) > 1:
		rnick = urllib.unquote(t[1])
	else:
		rnick = ''
	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
	show_groups = int(mam.config['show_groups'])
	show_offline = int(mam.config['show_offline'])
	realnick = ''
	
	# If I changed my state
	if email == mam.m.email and tid != mam.m.status:
		nick = mam.m.nick
		rnick = mam.m.nick
		realnick = mam.m.nick
		mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		mam.ui.printMsg('%s ' % _('Status set to'), mam.ui.COLORS.WHITE_R)
		mam.ui.printMsg('%s' % status, mam.ui.COLORS.CYAN_R)

	# If user changed his/her state, we change it in the our list
	# and log that in events pad.
	if tid != md.users[email].status:
		CheckOffline = 0
		if md.users[email].status in ['FLN', 'HDN']:
			CheckOffline = 1
		if show_groups:
			for g in mam.contactListManager.gList.grupos:
				found = 0
				for p in g.passports.passports:
					if p.name == email:
						found = 1
						old_status = p.status
						p.set_status(tid)
						if email not in mam.aliasesList.keys():
							p.set_nick(rnick)	# If not user defined
						nick = p.nick
						realnick = p.realnick
						if realnick <> rnick:
							p.set_realnick(rnick)
						user_index = mam.contactListManager.gList.grupos[mam.contactListManager.gList.grupos.index(g)].passports.passports.index(p)
						group_index = mam.contactListManager.gList.grupos.index(g)
						mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
						mam.ui.printMsg('%s' % nick, mam.ui.COLORS.WHITE_R)
						mam.ui.printMsg(' %s ' % _('changed status to'), mam.ui.COLORS.CYAN)
						mam.ui.printMsg('%s' % status, mam.ui.COLORS.CYAN_R)
						break
				if found:
					break
		else:
			for p in mam.contactListManager.pList.passports:
				if p.name == email:
					p.set_status(tid)
					if email not in mam.aliasesList.keys():
						p.set_nick(rnick)	# If not user defined
					nick = p.nick
					realnick = p.realnick
					if realnick <> rnick:
						p.set_realnick(rnick)
					mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
					mam.ui.printMsg('%s' % nick, mam.ui.COLORS.WHITE_R)
					mam.ui.printMsg(' %s ' % _('changed status to'), mam.ui.COLORS.CYAN)
					mam.ui.printMsg('%s' % status, mam.ui.COLORS.CYAN_R)
					break
		
		# If nick is user defined, include it in the same line
		if (email <> mam.m.email) and email in mam.aliasesList.keys() and int(mam.config['show_realnick_changes']) == 1:
			mam.ui.printMsg(' %s ' % _('with realnick'), mam.ui.COLORS.CYAN)
			mam.ui.printMsg('%s' % rnick, mam.ui.COLORS.CYAN_R)

		### We correct default_scrListpos.
		if mam.ui.scrList.default_scrListpos <> -1:
			# We get the data of the SELECTED user. Really not neccesary.
			if show_groups and not show_offline and mam.contactListManager.default_user <> -1:
				passport = mam.contactListManager.gList.grupos[mam.contactListManager.default_group].passports.passports[mam.contactListManager.default_user].name
				num_non_fln = mam.contactListManager.gList.grupos[mam.contactListManager.default_group].passports.countNonFLN()
			elif show_groups and mam.contactListManager.default_user <> -1:
				passport = mam.contactListManager.gList.grupos[mam.contactListManager.default_group].passports.passports[mam.contactListManager.default_user].name
				num_non_fln = mam.contactListManager.gList.grupos[mam.contactListManager.default_group].passports.size()
			elif not show_groups and show_offline:
				passport = mam.contactListManager.pList.passports[mam.contactListManager.default_user].name
				num_non_fln = mam.contactListManager.pList.size()
			elif not show_groups:
				passport = mam.contactListManager.pList.passports[mam.contactListManager.default_user].name
				num_non_fln = mam.contactListManager.pList.countNonFLN()
	
			# If the group of the user who connects its expanded and if
			# the default_user is below that user:
			if show_groups and old_status == 'FLN' and not show_offline and \
			mam.contactListManager.gList.grupos[group_index].expanded and (group_index < \
			mam.contactListManager.default_group or (group_index == mam.contactListManager.default_group and \
			user_index < mam.contactListManager.default_user)):
				mam.ui.scrList.default_scrListpos += 1
		else:
			mam.ui.scrList.default_scrListpos = 0
		if CheckOffline and not mam.contactListManager.userBlocked(email):
			mam.checkToSendOffline()
		
		# Chequeo conexion de usuario favorito y ejecuto accion
		if mam.favList.has_key(email) and old_status == 'FLN':
			os.system(mam.favList[email])

	else:
	# User changed his/her realnick
		if show_groups:
			for g in mam.contactListManager.gList.grupos:
				found = 0
				for p in g.passports.passports:
					if p.name == email:
						found = 1
						realnick = p.realnick
						nick = p.nick
						p.set_realnick(rnick)
						if email not in mam.aliasesList.keys():
							p.set_nick(rnick)	# If not user defined					
						break
				if found:
					break
		else:
			for p in mam.contactListManager.pList.passports:
				if p.name == email:
					p.set_realnick(rnick)
					#CHECK THIS! I check if I am in my own list and do proper changes
					#if md.email == email and mam.contactListManager.pList.passports.passinList(email) <> -1:
					realnick = p.realnick
					nick = p.nick
					p.set_realnick(rnick)
					if email not in mam.aliasesList.keys():
						p.set_nick(rnick)	# If not user defined
					break
		if realnick and rnick and realnick != rnick \
		and int(mam.config['show_realnick_changes']) == 1:
			mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
			mam.ui.printMsg('%s' % nick, mam.ui.COLORS.WHITE_R)
			mam.ui.printMsg(' %s ' % _('changed realnick to'), mam.ui.COLORS.CYAN)
			mam.ui.printMsg('%s' % rnick, mam.ui.COLORS.CYAN_R)
	
	# Update LST
	if email not in mam.aliasesList.keys() and email <> mam.m.email and nick <> rnick:
		mam.m.userren(email, rnick)

	# Refresh
	#if mam.ui.padArray.idactive == 0:
	#	relative_pos = mam.ui.scrList.default_scrListpos%(mam.ui.maxY-11)
	mam.ui.scrList.build_entire_scrList()#mam.ui.scrList.default_scrListpos - relative_pos)
	mam.ui.scrList.build_visible_scrList()
	#	if mam.ui.options_index == -1:
	#		mam.ui.scrList.print_scrList()
	#	else:
	#		mam.ui.rebuild_contactList_whileinMenu()
	#	mam.ui.padArray.refresh(_('EVENTS'))
	#elif mam.ui.padArray.idactive == 1:
	#	if mam.ui.options_index == -1:
	#		mam.ui.padArray.refresh(_('EVENTS'))
	#	else:
	#		#mam.ui.rebuild_eventsTab_whileinMenu()
	#		mam.ui.rebuild_tab_whileinMenu()
	#else:
	#	if mam.ui.options_index == -1:
	#		mam.ui.padArray.refresh(mam.ui.padArray.IdtoNom(mam.ui.padArray.idactive))
	#	else:
	#		mam.ui.rebuild_tab_whileinMenu()
	# For managing if a WINDOW option is open.
	mam.ui.refreshScr()
	msncb.cb_nln(md, type, tid, params)
	
def cb_fln(md, type, tid, params):
	email = tid
	show_groups = int(mam.config['show_groups'])
	show_offline = int(mam.config['show_offline'])
	
	# We change the status of the user who disconnected
	if show_groups:
		for g in mam.contactListManager.gList.grupos:
			found = 0
			for p in g.passports.passports:
				if p.name == email:
					found = 1
					p.set_status('FLN')					
					nick = p.nick
					user_index = mam.contactListManager.gList.grupos[mam.contactListManager.gList.grupos.index(g)].passports.passports.index(p)
					group_index = mam.contactListManager.gList.grupos.index(g)
					break
			if found:
				break
	else:
		for p in mam.contactListManager.pList.passports:
			if p.name == email:
				p.set_status('FLN')				
				nick = p.nick
				break				

	### We correct default_scrListpos.
	# We get the data of the selected user
	if show_groups and not show_offline and mam.contactListManager.default_user <> -1:
		passport = mam.contactListManager.gList.grupos[mam.contactListManager.default_group].passports.passports[mam.contactListManager.default_user].name
		num_non_fln = mam.contactListManager.gList.grupos[mam.contactListManager.default_group].passports.countNonFLN()
	elif show_groups and mam.contactListManager.default_user <> -1:
		passport = mam.contactListManager.gList.grupos[mam.contactListManager.default_group].passports.passports[mam.contactListManager.default_user].name
		num_non_fln = mam.contactListManager.gList.grupos[mam.contactListManager.default_group].passports.size()
	elif not show_groups and show_offline:
		passport = mam.contactListManager.pList.passports[mam.contactListManager.default_user].name
		num_non_fln = mam.contactListManager.pList.size()
	elif not show_groups:
		passport = mam.contactListManager.pList.passports[mam.contactListManager.default_user].name
		num_non_fln = mam.contactListManager.pList.countNonFLN()
	else:
		passport = ''
		num_non_fln = ''

	# If not show_groups and if im at the end of the entire list.	
	if not show_groups and mam.ui.scrList.default_scrListpos == \
	mam.ui.scrList.list_lines:
			mam.ui.scrList.default_scrListpos -= 1
			mam.contactListManager.default_user -= 1
	elif show_groups:
		# If the selected is the user who disconnects and if its the last 
		# of the group
		if passport <> '' and num_non_fln <> '' and passport == email and mam.contactListManager.default_user \
		== num_non_fln and mam.ui.scrList.default_scrListpos <> -1:
			mam.ui.scrList.default_scrListpos -= 1
			mam.contactListManager.default_user -= 1
			#mam.ui.padInput.addstr('1')
			#mam.ui.padInput.refresh()
		# If im in the last line and that is the user who disconnects
		elif mam.contactListManager.gList.grupos[group_index].expanded and \
		group_index == mam.contactListManager.default_group and user_index == mam.contactListManager.default_user:
			#mam.ui.padInput.addstr('2')
			#mam.ui.padInput.refresh()
			mam.contactListManager.default_user -= 1
			mam.ui.scrList.default_scrListpos -= 1		
		# Or if the group of the user who disconnects its expanded and if
		# the default_user is below that user:
		elif not show_offline and mam.contactListManager.gList.grupos[group_index].expanded and \
		(group_index < mam.contactListManager.default_group or (group_index == mam.contactListManager.default_group \
		and user_index < mam.contactListManager.default_user)):
			mam.ui.scrList.default_scrListpos -= 1
			if group_index == mam.contactListManager.default_group and user_index < mam.contactListManager.default_user:
				mam.contactListManager.default_user -= 1
			#mam.ui.padInput.addstr('3')
			#mam.ui.padInput.refresh()
		# Or if the group of the user who disconnects its expanded and if
		# the default user is above that user:
		elif not show_offline and mam.contactListManager.gList.grupos[group_index].expanded and \
		(group_index > mam.contactListManager.default_group or (group_index == mam.contactListManager.default_group \
		and user_index > mam.contactListManager.default_user)):
			pass
			#mam.ui.scrList.default_scrListpos -= 1
			#mam.ui.padInput.addstr('4')
			#mam.ui.padInput.refresh()		
	
	# Log in events pad
	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
	mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
	mam.ui.printMsg('%s (%s)' % (nick, email), mam.ui.COLORS.WHITE_R)
	mam.ui.printMsg(' %s' % _('disconnected'), mam.ui.COLORS.CYAN)
	
	u = mam.m.users[email]
	if u.sbd and u.sbd.msgqueue:
		mam.ui.printMsg('\n%s ' % _('The following messages for'), mam.ui.COLORS.CYAN)
		mam.ui.printMsg('%s ' % nick, mam.ui.COLORS.WHITE_R)
		mam.ui.printMsg('%s: ' % _('will be discarded'), mam.ui.COLORS.CYAN)

		for msg in u.sbd.msgqueue:
			mam.ui.printMsg('\n%s' % msg, mam.ui.COLORS.WHITE)
	
	# Refresh list and/or other stuff
	#if mam.ui.padArray.idactive == 0:
	#	relative_pos = mam.ui.scrList.default_scrListpos%(mam.ui.maxY-11)
	mam.ui.scrList.build_entire_scrList()#mam.ui.scrList.default_scrListpos - relative_pos)
	mam.ui.scrList.build_visible_scrList()
	#	if mam.ui.options_index == -1:
	#		mam.ui.scrList.print_scrList()
	#	else:
	#		mam.ui.rebuild_contactList_whileinMenu()
	#elif mam.ui.padArray.idactive <> 1:
		#if mam.ui.options_index == -1:
		#	mam.ui.padArray.refresh(mam.ui.padArray.IdtoNom(mam.ui.padArray.idactive))
		#else:
		#	mam.ui.rebuild_tab_whileinMenu()
	#mam.ui.padArray.refresh(_('EVENTS'))
	mam.ui.refreshScr()
	msncb.cb_fln(md, type, tid, params)
	
	# For managing if a WINDOW option is open.
	#mam.ui.refreshScr(0, 0, 0, 1)

def cb_out(md, type, tid, params):
	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
	mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
	mam.ui.printMsg('%s. ' % _('Server sent disconnect'), mam.ui.COLORS.YELLOW)
	mam.ui.printMsg('%s.\n' % _('You probably logged in from somewhere else'), mam.ui.COLORS.WHITE_R)
	mam.m.status = 'FLN'

	# not connected anymore
	mam.connectStatus = 0

	# disable options in menu
	mam.ui.options.list[mam.ui.options.nametoIndex(_('Change nick'))].available = 0
	mam.ui.options.list[mam.ui.options.nametoIndex(_('Change configuration'))].available = 0
	#mam.ui.options.list[mam.ui.options.nametoIndex(_('Files transfer'))].available = 0
	#mam.ui.options.list[mam.ui.options.nametoIndex(_('Show logs'))].available = 0
	#mam.ui.options.list[mam.ui.options.nametoIndex(_('Show lists'))].available = 0
	mam.ui.options.list[mam.ui.options.nametoIndex(_('Handle contacts/groups'))].available = 0

	if mam.ui.padArray.idactive == 1 and mam.ui.options_index == -1:
		mam.ui.rebuild_tab_whileinMenu()
	else:
		mam.ui.padArray.refresh(_('EVENTS'))
	mam.ui.status='FLN'
	mam.ui.refreshScr()
	mam.ui.padArray.refresh(_('CONTACTS'))
	msncb.cb_out(md, type, tid, params)

def cb_rng(md, type, tid, params):
	t = params.split(' ')
	nick = urllib.unquote(t[4])
	show_picture = int(mam.config['show_picture'])
	show_ring = int(mam.config['show_ring'])
	show_groups = int(mam.config['show_groups'])
	
	# Check if user is blocking you or is hidden
	if show_groups:
		status = mam.contactListManager.gList.userStatus(t[3])		
	else:
		status = mam.contactListManager.pList.userStatus(t[3])
	if status == 'FLN':
		ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
		mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		mam.ui.printMsg('%s ' % nick, mam.ui.COLORS.WHITE_R)
		mam.ui.printMsg('%s.' % _('is hidden or blocking you'), mam.ui.COLORS.YELLOW)

	# Let know about the ring
	if not show_picture and show_ring:
		ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
		mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		mam.ui.printMsg('%s ' % nick, mam.ui.COLORS.WHITE_R)
		mam.ui.printMsg('%s' % _('is ringing you'), mam.ui.COLORS.YELLOW)
		if mam.ui.padArray.idactive == 1 and mam.ui.options_index == -1:
			mam.ui.rebuild_tab_whileinMenu()
		else:
			mam.ui.padArray.refresh(_('EVENTS'))
	
		# For managing if a WINDOW option is open.
		mam.ui.refreshScr(0, 0, 0, 1)
	msncb.cb_rng(md, type, tid, params)

def cb_joi(md, type, tid, params, sbd):
	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
	email = tid
	index = -1
	for p in mam.ui.padArray.wins:
		if p.passport == email:
			index = mam.ui.padArray.wins.index(p)
			nick = mam.ui.padArray.wins[index].nombre
			break
	if index <> -1:
		# unset waiting to join conversation flag
		mam.ui.padArray.wins[index].unset_waitingJoi()

	# We print the msg/msg's in screen
	all_msg = ''
	for msg in sbd.msgqueue:
		msg = msg.split('*')[0]
		if index <> -1:
			mam.ui.padArray.wins[index].ventana.addstr("\n", mam.ui.COLORS.WHITE)
			mam.ui.padArray.wins[index].ventana.addstr(ctime + " >> ", mam.ui.COLORS.WHITE)
			mam.ui.padArray.wins[index].ventana.addstr(msg, mam.ui.COLORS.BLACK_R)
		all_msg += msg

	# Check if it was an offline message
	if index == -1:
		mam.deleteFlnMsg(email)

	msncb.cb_joi(md, type, tid, params, sbd)
	mam.ui.refreshScr(1, 1, 1, 1, 1)

	# We dump msg to file
	if mam.config.has_key('conversations_log_path'):
		dtime = time.strftime('%d/%m/%Y', time.localtime()) + ' ' + ctime
		mam.dumptoFile(str(mam.config['conversations_log_path']) + email, dtime + ' >> ' + all_msg)

def cb_iro(md, type, tid, params, sbd):
	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
	email = tid
	for p in mam.ui.padArray.wins:
		if p.passport == email:
			index = mam.ui.padArray.wins.index(p)
			nick = mam.ui.padArray.wins[index].nombre
			break
	mam.ui.padArray.wins[index].unset_waitingJoi()	# unset waiting to join flag

	# We print the msg/msg's in screen
	all_msg = ''
	for msg in sbd.msgqueue:
		if sbd.msgqueue.index(msg) <> 0:
			mam.ui.padArray.wins[index].ventana.addstr("\n", mam.ui.COLORS.WHITE)
		msg = msg.split('*')[0]
		mam.ui.padArray.wins[index].ventana.addstr(" >> ", mam.ui.COLORS.WHITE)
		mam.ui.padArray.wins[index].ventana.addstr(msg, mam.ui.COLORS.BLACK_R)
		all_msg += msg
	msncb.cb_iro(md, type, tid, params, sbd)
	mam.ui.refreshScr(1, 1, 1, 1, 1)

	# We dump msg to file
	if mam.config.has_key('conversations_log_path'):
		dtime = time.strftime('%d/%m/%Y', time.localtime()) + ' ' + ctime
		mam.dumptoFile(str(mam.config['conversations_log_path']) + email, dtime + ' >> ' + all_msg)
	
def cb_bye(md, type, tid, params, sbd):
	email = tid
	nick = ''

	# Pidgin (ex Gaim) does not send Bye MSG in DP transfer
	# we delete the dp base object
	if int(mam.config['show_picture']):
		mam.dpManager.delSession(email)

	if int(mam.config['show_picture']) <> 0 or not \
	int(mam.config['show_close_chat']) <> 1:
		msncb.cb_bye(md, type, tid, params, sbd)	
		return

	# Here we could move around the entire contact list to get the nick.
	for p in mam.ui.padArray.wins:
		if p.passport == email:
			index = mam.ui.padArray.wins.index(p)
			nick = mam.ui.padArray.wins[index].nombre
			break
	if nick == '':
		nick = email
	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
	mam.ui.printMsg('\n%s' % ctime, mam.ui.COLORS.WHITE)
	mam.ui.printMsg(' %s' % nick, mam.ui.COLORS.WHITE_R)
	mam.ui.printMsg(' %s' % _('closed chat window'), mam.ui.COLORS.CYAN)
	if mam.ui.padArray.idactive == 1 and mam.ui.options_index == -1:
		mam.ui.rebuild_tab_whileinMenu()
	else:
		mam.ui.padArray.refresh(_('EVENTS'))
	mam.ui.refreshScr(0, 0, 0, 1)
	msncb.cb_bye(md, type, tid, params, sbd)

def cb_msg(md, type, tid, params, sbd):
	msncb.cb_msg(md, type, tid, params, sbd)

	t = tid.split(' ')
	email = t[0]

	# parse
	lines = params.split('\n')
	headers = {}
	eoh = 0
	for i in lines:
		# end of headers
		if i == '\r':
			break
		tv = i.split(':', 1)
		type = tv[0]
		value = tv[1].strip()
		headers[type] = value
		eoh += 1
	eoh +=1

	# handle special hotmail messages
	if email == 'Hotmail':
		if not headers.has_key('Content-Type'):
			return
		hotmail_info = {}

		# parse the body
		for i in lines:
			i = i.strip()
			if not i:
				continue
			tv = i.split(':', 1)
			type = tv[0]
			value = tv[1].strip()
			hotmail_info[type] = value

		msnlib.debug(params)
		if headers['Content-Type'] == 'text/x-msmsgsinitialemailnotification; charset=UTF-8':
			newmsgs = int(hotmail_info['Inbox-Unread'])
			if not newmsgs:
				return
			ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
			mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
			mam.ui.printMsg('%s ' % _('You have'), mam.ui.COLORS.STARTUP)
			mam.ui.printMsg('%s ' % str(newmsgs), mam.ui.COLORS.WHITE_R)			
			mam.ui.printMsg('%s' % _('unread emails in your Hotmail account'), mam.ui.COLORS.STARTUP)
			mam.ui.padArray.refresh(_('EVENTS'))
			mam.ui.padInput.refresh()

		elif headers['Content-Type'] == 'text/x-msmsgsemailnotification; charset=UTF-8':
			ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
			from_name = hotmail_info['From']
			from_addr = hotmail_info['From-Addr']
			subject = hotmail_info['Subject']
			mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
			mam.ui.printMsg('%s: ' % _('You have just received an email'), mam.ui.COLORS.WHITE_R)
			mam.ui.printMsg('\n\t' + '%s: ' % _('From') + '%s (%s)\n\t' % (from_name, from_addr) + '%s: ' % _('Subject') + subject, mam.ui.COLORS.CYAN)
			mam.ui.padArray.refresh(_('EVENTS'))
			mam.ui.padInput.refresh()
			if mam.config.has_key('action_mail'):
				os.system(mam.config['action_mail'])
			mam.ui.refreshScr(0, 0, 0, 0, 0)
		return	

	# typing notices
	if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol':
		nick = urllib.unquote(t[1])
		if not nick:
			nick = email
		if not mam.m.users[email].priv.has_key('typing'):
			mam.m.users[email].priv['typing'] = 0

		#if not mam.m.users[email].priv['typing']:
		# I search the tab throw all of them
		index = -1
		for p in mam.ui.padArray.wins:
			if p.passport == email:
				index = mam.ui.padArray.wins.index(p)
				break
		if (index == -1):
		#and mam.m.users[email].priv['typing'] == 0) \
		#or (index == -1 and (mam.m.users[email].priv['typing'] \
		#- datetime.timedelta(seconds = 4) < datetime.datetime.now())):
			ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
			mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
			mam.ui.printMsg('%s ' % nick, mam.ui.COLORS.WHITE_R)
			mam.ui.printMsg('%s' % _('is typing'), mam.ui.COLORS.YELLOW)
			mam.ui.padArray.refresh(_('EVENTS'))
			mam.ui.padInput.refresh()
		else:
			mam.ui.padArray.wins[index].set_typingFlag()
		mam.m.users[email].priv['typing'] = datetime.datetime.now() + datetime.timedelta(seconds = 10)
		mam.ui.sendSignal("type_alarm", 12)
		mam.ui.refreshScr()	# Refresh screen
		
	# ignore the x-clientcaps messages generated from gaim / amsn
	elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-clientcaps':
		return

	# ignore emoticons
	elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-mms-animemoticon':
		return

	# got ft invitation / ft data / dp msg
	elif headers.has_key('Content-Type') and headers['Content-Type'] == 'application/x-msnmsgrp2p':
		parameters = msnft.getParameters(params)
		# got ft invitation
		if 'AppID: 2' in params and 'Context' in params:
			pass
		#	# Debug: print ft sessions
		#	mam.ftManager.listSessions()
		#	# Parse context
		#	i = 4-(len(parameters['Context'])%4)
		#	context = parameters['Context']
		#	for e in range(i):
		#		context = context + "="
		#	context = msnft.FTContext(base64.b64decode(context))
		#	# Print ft transfer data
		#	nick = urllib.unquote(t[1])
		#	if not nick: 
		#		nick = email
		#	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
		#	mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		#	mam.ui.printMsg('%s ' % str(nick), mam.ui.COLORS.WHITE_R)
		#	mam.ui.printMsg('%s ' % _('wants to send you the file'), mam.ui.COLORS.YELLOW)
		#	mam.ui.printMsg('%s ' % str(context.filename), mam.ui.COLORS.CYAN)
		#	mam.ui.printMsg('(', mam.ui.COLORS.WHITE_R)
		#	mam.ui.printMsg('%s bytes' % str(context.file_size), mam.ui.COLORS.CYAN_R)
		#	mam.ui.printMsg(')', mam.ui.COLORS.WHITE_R)
		#	mam.ui.padArray.refresh(_('EVENTS'))
		#	mam.ui.padInput.refresh()
		#	# Process new invitation in msnft
		#	# TODO Ahora: auto accept the file transfer:
		#	mam.ftManager.process(mam, tid, params, sbd, parameters)
		#	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
		#	mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		#	mam.ui.printMsg('%s ' % _('Accepted file transfer with'), mam.ui.COLORS.YELLOW)
		#	mam.ui.printMsg('%s ' % str(nick), mam.ui.COLORS.WHITE_R)
		#	mam.ui.padArray.refresh(_('EVENTS'))
		#	mam.ui.padInput.refresh()
		# got ft msg
		elif mam.ftManager.gotFTData(parameters):
			pass
		#	# Debug: print ft sessions
		#	mam.ftManager.listSessions()
		#	mam.ftManager.process(mam, tid, params, sbd, parameters)		
		# got dp invitation
		elif 'AppID: 1' in params and 'Content-Type: application/x-msnmsgr-sessionreqbody' in params:
			# Debug: print dp sessions
			mam.dpManager.listSessions()
			mam.dpManager.process(mam, tid, params, sbd)
		# got dp msg
		elif mam.dpManager.hasSessionWith(t[0]):
			# Debug: print dp sessions
			mam.dpManager.listSessions()
			mam.dpManager.process(mam, tid, params, sbd)

	# got nudge
	elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msnmsgr-datacast'\
	and 'ID: 1' in params:
		nick = urllib.unquote(t[1])
		if not nick: 
			nick = email
		ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
		mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		mam.ui.printMsg('%s ' % nick, mam.ui.COLORS.WHITE_R)
		mam.ui.printMsg('%s' % _('sent you a nudge'), mam.ui.COLORS.YELLOW)
		mam.ui.padArray.refresh(_('EVENTS'))
		mam.ui.padInput.refresh()
		if mam.config.has_key('action_nudge'):
			os.system(mam.config['action_nudge'])

	# plain messages
	else:
		mam.m.users[email].priv['typing'] = 0		
		index = -1
		ctime = time.strftime(mam.config['timestamp_format'], time.localtime())

		# I search the tab throw all of them
		for p in mam.ui.padArray.wins:
			if p.passport == email:
				index = mam.ui.padArray.wins.index(p)
				break

		# if no tab with that user, we open a new tab
		if index == -1:
			nick = urllib.unquote(t[1])
			mam.ui.padArray.newWin(nick, email)
			index = mam.ui.padArray.size() - 1
			mam.ui.padArray.wins[index].set_passport(email)
			if mam.config.has_key('action_chat'):
				os.system(mam.config['action_chat'])

		# We print the msg	
		#(y, x) = mam.ui.padArray.wins[mam.ui.padArray.idactive].ventana.p.getyx()
		#if x <> 0 and y <> 0:
		#t = mam.ui.padArray.wins[mam.ui.padArray.idactive].ventana.scroll
		mam.ui.padArray.wins[index].ventana.addstr("\n", mam.ui.COLORS.WHITE)
		mam.ui.padArray.wins[index].ventana.addstr(ctime, mam.ui.COLORS.WHITE)
		if len(lines[eoh:]) == 1:
			mam.ui.padArray.wins[index].ventana.addstr(" << ", mam.ui.COLORS.BLUE_R)
			mam.ui.padArray.wins[index].ventana.addstr(lines[eoh], mam.ui.COLORS.WHITE)
			dump_msg = lines[eoh]
		else:
			mam.ui.padArray.wins[index].ventana.addstr("\n" + " << ", mam.ui.COLORS.BLUE_R)
			msg = string.join(lines[eoh:], '\n\t')
			msg = msg.replace('\r', '')
			mam.ui.padArray.wins[index].ventana.addstr(msg, mam.ui.COLORS.WHITE)
			dump_msg = msg

		# We dump the msg to file
		if mam.config.has_key('conversations_log_path'):
			dtime = time.strftime('%d/%m/%Y', time.localtime()) + ' ' + ctime
			mam.dumptoFile(mam.config['conversations_log_path'] + email, dtime + ' <<<< ' + dump_msg)

		# We set New_Msg flag
		if mam.ui.padArray.idactive <> index:
			mam.ui.padArray.wins[index].set_newMsgFlag()
		mam.ui.padArray.wins[index].unset_typingFlag()

		# Refresh screen
		mam.ui.refreshScr(1, 1, 0, 1)
		if len(sbd.emails) > 1:
			users = sbd.emails
		#msncb.cb_msg(md, type, tid, params, sbd)
	
def cb_err(md, errno, params):
	if errno not in [913, 217, 224]:
		if not msncb.error_table.has_key(errno):
			desc = 'Unknown'
		else:
			desc = msncb.error_table[errno]
		ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
		mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		mam.ui.printMsg('%s ' % _('Server sent error') +  "%d: %s." % (errno, desc), mam.ui.COLORS.RED_R)
		if mam.ui.padArray.idactive == 1 and mam.ui.options_index == -1:
			mam.ui.rebuild_tab_whileinMenu()
		else:
			mam.ui.padArray.refresh(_('EVENTS'))
		mam.ui.refreshScr()
		msncb.cb_err(md, errno, params)
		time.sleep(3)
		mam.ui.quit(1)

# Ping response
def cb_qng(md, type, tid, params):
	mam.nextPing = datetime.datetime.now() + datetime.timedelta(seconds = int(tid))
	msncb.cb_qng(md, type, tid, params)
	mam.ui.padInput.refresh()

def cb_add(md, type, tid, params):
	t = params.split(' ')
	type = t[0]
	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
	if type == 'RL' or type == 'FL':
		email = t[2]
		nick = urllib.unquote(t[3])
	if type == 'RL':
		# I add who adds me to my own list
		if mam.config.has_key('auto_add'):
			mam.m.useradd(email, email, '0')

		# refresh 
		mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		mam.ui.printMsg('%s (%s) ' % (email, nick), mam.ui.COLORS.BLUE_RI)
		mam.ui.printMsg('%s' % _('has added you to his contact list'), mam.ui.COLORS.MSG_ADD)
		mam.ui.refreshScr()
		msncb.cb_add(md, type, tid, params)
	elif type == 'FL':
		# I check if that user I added was a new contact or if it was a nick change:
		found = 0
		if int(mam.config['show_groups']):
				for g in mam.contactListManager.gList.grupos:
					for p in g.passports.passports:
						if p.name == email:
							found = 1
							break
					if found:
						break
		else:
				for p in mam.contactListManager.pList.passports:			
					if p.name == email:
						found = 1
						break
		#if found:
		#	mam.ui.refreshScr()
		#	return
			
		# If I added a new user
		mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		mam.ui.printMsg('%s (%s) ' % (email, nick), mam.ui.COLORS.BLUE_R)
		mam.ui.printMsg('%s' % _('has been added to your contact list'), mam.ui.COLORS.MSG_ADD2)
		msncb.cb_add(md, type, tid, params)
		mam.ui.scrList.entireList = []
		mam.ui.scrList.visibleList = []
		mam.ui.scrList.default_scrListpos = 0
		mam.ui.scrList.list_lines = 0
		mam.contactListManager.rebuild()
		mam.ui.scrList.build_entire_scrList()
		mam.ui.refreshScr()

def cb_rem(md, type, tid, params):
	t = params.split(' ')
	type = t[0]
	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
	if type == 'RL' or type == 'FL':
		email = t[2]
	if type == 'RL':
		mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		mam.ui.printMsg('%s ' % email, mam.ui.COLORS.RED_RI)
		mam.ui.printMsg('%s' % _('has removed you from his/her list'), mam.ui.COLORS.MSG_DEL)
		if mam.ui.padArray.idactive == 1 and mam.ui.options_index == -1:
			mam.ui.rebuild_tab_whileinMenu()
		else:
			mam.ui.padArray.refresh(_('EVENTS'))
		mam.ui.refreshScr(0, 0, 0, 1)
		msncb.cb_rem(md, type, tid, params)
	elif type == 'FL':
		mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
		mam.ui.printMsg('%s ' % email, mam.ui.COLORS.BLUE_R)
		mam.ui.printMsg('%s' % _('has been removed from your contact list'), mam.ui.COLORS.MSG_DEL2)
		if mam.ui.padArray.idactive == 1 and mam.ui.options_index == -1:
			mam.ui.rebuild_tab_whileinMenu()
		else:
			mam.ui.padArray.refresh(_('EVENTS'))
		msncb.cb_rem(md, type, tid, params)
		mam.ui.scrList.default_scrListpos = 0
		mam.contactListManager.rebuild()
		relative_pos = mam.ui.scrList.default_scrListpos%(mam.ui.maxY-11)
		mam.ui.scrList.build_entire_scrList(mam.ui.scrList.default_scrListpos - relative_pos)
		mam.ui.scrList.build_visible_scrList()
		mam.ui.scrList.print_scrList()
		mam.ui.refreshScr(0, 0, 0, 1)		

def cb_adg(md, type, tid, params):
	t = params.split(' ')
	lver, name, gid = t[0:3]
	name = urllib.unquote(name)
	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
	mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
	mam.ui.printMsg(_('Group') + ' %s (%s) ' % (name, gid), mam.ui.COLORS.BLUE_R)
	mam.ui.printMsg('%s' % _('has been added'), mam.ui.COLORS.MSG_ADD2)
	mam.ui.padArray.refresh(_('EVENTS'))
	msncb.cb_adg(md, type, tid, params)
	if int(mam.config['show_groups']) == 1:
		mam.contactListManager.default_user = -1
		mam.contactListManager.default_group = 0
		mam.ui.scrList.default_scrListpos = 0
		mam.ui.scrList.list_lines = 0
		mam.contactListManager.rebuild()
		relative_pos = mam.ui.scrList.default_scrListpos%(mam.ui.maxY-11)
		mam.ui.scrList.build_entire_scrList(mam.ui.scrList.default_scrListpos - relative_pos)
		mam.ui.scrList.build_visible_scrList()
		mam.ui.scrList.print_scrList()		
		mam.ui.padInput.refresh()
		
def cb_rmg(md, type, tid, params):
	t = params.split(' ')
	lver, gid = t[0:2]
	name = md.groups[gid]
	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
	mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
	mam.ui.printMsg(_('Group') + ' %s (%s) ' % (name, gid), mam.ui.COLORS.BLUE_R)
	mam.ui.printMsg('%s' % _('has been removed'), mam.ui.COLORS.MSG_DEL2)
	mam.ui.padArray.refresh(_('EVENTS'))
	msncb.cb_rmg(md, type, tid, params)
	if int(mam.config['show_groups']) == 1:
		mam.contactListManager.default_user = -1
		mam.contactListManager.default_group = 0
		mam.ui.scrList.default_scrListpos = 0
		mam.ui.scrList.list_lines = 0
		mam.contactListManager.rebuild()
		relative_pos = mam.ui.scrList.default_scrListpos%(mam.ui.maxY-11)
		mam.ui.scrList.build_entire_scrList(mam.ui.scrList.default_scrListpos - relative_pos)
		mam.ui.scrList.build_visible_scrList()
		mam.ui.scrList.print_scrList()		
		mam.ui.padInput.refresh()

def cb_reg(md, type, tid, params):
	t = params.split(' ')
	gid = t[1]
	origname = md.groups[gid]
	origname = urllib.unquote(origname)
	newname = t[2]
	newname = urllib.unquote(newname)
	ctime = time.strftime(mam.config['timestamp_format'], time.localtime())
	mam.ui.printMsg('\n%s ' % ctime, mam.ui.COLORS.WHITE)
	mam.ui.printMsg(_('Group') + ' %s (%s) ' % (origname, gid), mam.ui.COLORS.BLUE_R)
	mam.ui.printMsg('%s ' % _('has been renamed to'), mam.ui.COLORS.WHITE_R)
	mam.ui.printMsg('%s' % newname, mam.ui.COLORS.BLUE_R)
	mam.ui.padArray.refresh(_('EVENTS'))
	msncb.cb_reg(md, type, tid, params)
	if int(mam.config['show_groups']) == 1:
		mam.ui.scrList.default_scrListpos = 0
		mam.ui.scrList.list_lines = 0
		relative_pos = mam.ui.scrList.default_scrListpos%(mam.ui.maxY-11)
		mam.contactListManager.rebuild()
		mam.ui.scrList.build_entire_scrList(mam.ui.scrList.default_scrListpos - relative_pos)
		mam.ui.scrList.build_visible_scrList()
		mam.ui.scrList.print_scrList()		
		mam.ui.padInput.refresh()
